package com.token.sysflow.core;
import com.token.sql.IntegrateSql;
import com.token.sysflow.enumerate.ApprovalTypeEnum;
import com.token.sysflow.exception.ErrorCodeEnum;
import com.token.sysflow.exception.FlowException;
import com.token.sysflow.impl.AbstractFlowHandlerImpl;

/**
 * 取回流程
 * @author chenjianxiong 2020/4/13
 */
public class BackFlow extends AbstractFlowCore{
    public BackFlow(IntegrateSql f, String keyUnid) throws Exception{
        super(f,keyUnid);
    }


    @Override
    public void execute(AbstractFlowHandlerImpl flowHandler) throws Exception{

        //除了普通审批，其它类型不能取回。
        if(approveProcess.getApprovalType() != ApprovalTypeEnum.SP.getId()){
            throw new FlowException(ErrorCodeEnum.BACK_CONFIG_NO);
        }

        //退回状态
        if(approveProcess.isReturned()){
            throw new FlowException(ErrorCodeEnum.RETURN_CONFIG_NO);
        }

        //初始化起草人、申请人、当前人。
        initUserInfo(approveProcess.getCreater(),approveProcess.getApplyer(),flowHandler.getActionUser());

        //判断当前用户是否是上一环节的当前办理人
        if(!approveProcess.getApproves(approveProcess.getPreStepId()).contains(flowHandler.getActionUser())){
            throw new FlowException(ErrorCodeEnum.BACK_CHECK_PREAPPROVE);
        }

        //判断开关
        if(!getFromStep().isCanBack()){
            throw new FlowException(ErrorCodeEnum.CONFIG_BACK);
        }

        //设置目标流程环节
        super.setToFlowById(approveProcess.getPreFlowId());

        //设置目标环节
        super.setToStepById(approveProcess.getPreStepId());

        //删除当前的办理人
        approveProcess.delStepAllApproves(approveProcess.getStep());

        //更新审批数据
        super.updateApproveProcess(flowHandler);

        //写入办理人
        approveProcess.addToStepApprover(flowHandler.getActionUser());

        //添加输出参数
        approveProcess.appendFlowProcessInfo(toFlow,toStep);

        //生成新的流转记录和办理意见
        super.createFlowApproveLog(flowHandler);

        //处理知会
        this.handleSystemNotify("流程取回","单据【"+ approveProcess.getFlowNo() +"】有用户操作了“取回”，原因是："+ flowHandler.getOpinions() +"。",flowRecord.getFlowRecordApprovers());
    }
}
